package designpattern.structural_patterns;

import java.util.ArrayList;
import java.util.List;

public class CompositePattern {

	interface Component{
		void operation();
	}
	
	public class Leaf implements Component{
		@Override
		public void operation() {
			System.out.print("Leaf\n");
		}
	}
	
	public abstract class BaseComposite implements Component{
		public abstract void add(Component component);
		public abstract void remove(Component component);
		public abstract Component getChild(int index);
	}
	
	public class Composite extends BaseComposite{
		private List lstNode = new ArrayList();
		@Override
		public void add(Component component) {
			lstNode.add(component);
		}
		@Override
		public Component getChild(int index) {
			return (Component)lstNode.get(index);
		}
		@Override
		public void remove(Component component) {
			lstNode.remove(component);
		}
		@Override
		public void operation() {
			System.out.print("Composite\n");
			for(Object obj : lstNode) {
				((Component)obj).operation();
			}
		}
		
	}
	
	public static void main(String[] args) {
		CompositePattern compositePattern = new CompositePattern();
		Composite root = compositePattern.new Composite();
		root.add(compositePattern.new Composite());
		root.add(compositePattern.new Composite());
		root.add(compositePattern.new Leaf());
		root.add(compositePattern.new Leaf());
		Composite child1 = compositePattern.new Composite();
		child1.add(compositePattern.new Leaf());
		child1.add(compositePattern.new Leaf());
		child1.add(compositePattern.new Leaf());
		root.add(child1);
		//
		root.operation();
	}

}
